#!/bin/sh
#
# Perform necessary twindb-backup setup steps
# after package is installed.
#

PROGNAME=`basename $0`
INSTALL_DIR=/opt/twindb-backup
CONFIG_DIR=/etc/twindb
LOG_DIR=/var/log/twindb-backup
PREFIX="/usr"

DISTRIBUTION=$(grep -Eo "(Debian|Ubuntu|RedHat|CentOS|openSUSE|Amazon|SUSE)" /etc/issue 2>/dev/null || uname -s)

error_exit()
{
  echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
  exit 1
}

mkdir -p "${LOG_DIR}" || error_exit "Cannot create ${LOG_DIR}!"

# setup config
if [ ! -e "${CONFIG_DIR}/twindb-backup.cfg" ]; then
  mkdir -p ${CONFIG_DIR} || error_exit "Cannot create ${CONFIG_DIR}!"
  mv "${INSTALL_DIR}/twindb-backup.cfg" "${CONFIG_DIR}/twindb-backup.cfg"
  chmod 600 "${CONFIG_DIR}/twindb-backup.cfg"
else
  echo "Skipping setting up of ${CONFIG_DIR}/twindb-backup.cfg as it already exists."
fi

# setup cron
if [ ! -e /etc/cron.d/twindb-backup ]; then
  mv "${INSTALL_DIR}/twindb-backup.cron" /etc/cron.d/twindb-backup
else
  echo "Skipping setting up of /etc/cron.d/twindb-backup as it already exists."
fi

# setup links to the executables

ln -sf "${INSTALL_DIR}/embedded/bin/twindb-backup" "${PREFIX}/bin/twindb-backup"

chown -Rh 0:0 "${INSTALL_DIR}"

echo "Thank you for installing twindb-backup!"

exit 0
